import { createRouter, createWebHashHistory } from "vue-router";
import { useStore } from "@/stores/user";
import { menuStore } from "@/stores/menu";
import baseRoutes from "./baseRoutes.js";
import shoperRoutes from "./shoperRoutes.js"
import workerRoute from "./workerRoute.js";
import managerRoutes from "./managerRoutes.js"
const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login.vue"),
    meta: {
      title: "登录",
      index: 1,
    },
  },
  {
    path: "/:catchAll(.*)",
    // name: "NotFound",//不能有，4.0以上不需要手动push404页面，直接这里这样配置404
    meta: {
      title: "NotFound",
    },
    component: () => import("@/views/404.vue"),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});
export function resetRouter() {
  const newRouter = createRouter({
    history: createWebHashHistory(),
    routes: routes,
  });
  router.matcher = newRouter.matcher; // reset router
}
// 路由白名单
const whiteList = ["/login", "/register"];
router.beforeEach(async (to, from, next) => {
  // const title = to.meta.title;
  // document.title = title;
  const token = localStorage.getItem("token");
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const store = useStore();
      const hasGetUserInfo = store.getUserInfo.userName;
      if (hasGetUserInfo != "" && hasGetUserInfo != null && hasGetUserInfo != undefined && hasGetUserInfo != "undefined") {
        //信息拿到后，用户请求哪就跳转哪
        next();
      } else {
        try {
          await store.getInfo();
          //************************************************请求方式获取路由表
          const store_menu = menuStore();
          // 这里就是根据角色来改变对应路由
          const {tabList,routes} = managerRoutes
          const menuList = tabList
          store_menu.setOrderNavTree(menuList);
          const accessRoutes = [
            // 所有未定义路由，全部重定向到404页
            ...routes,
          ];
          // const accessRoutes = await store.generateRoutes();
          // router.addRoutes(accessRoutes)//vue-router 4.0以下,4.0以上addroutes 已经废弃
          for (let item of accessRoutes) {
            //vue-router 4.0及以上
            router.addRoute(item);
          }
          next({ ...to, replace: true });
        } catch (error) {
          // 如果出错了，把令牌去掉，并让用户重新去到登录页面
          await store.resetToken();
          console.log(error || "Has Error");
          next(`/login?redirect=${to.path}`);
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // 如果这个页面不在白名单里，直接跳转到登录页面
      next(`/login?redirect=${to.path}`);
    }
  }
});
export default router;
